/**
* @Title: warning_ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @date 2014年10月27日 下午4:43:38
* @version V1.0
*/
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('CaseAduitProjectAddCtrl', ['$scope','CommunityService','WarningScreenService','CaseAuditDispathReviewDetailResultService','WarningAddService','CaseCommonService','$http','$modal','CaseAuditProjectAddService','$state','BaseURL','Modal','FwaTabsetService','$stateParams','AuditDictServices',
	                                function($scope,CommunityService,WarningScreenService,CaseAuditDispathReviewDetailResultService,WarningAddService,CaseCommonService,$http,$modal,CaseAuditProjectAddService,$state,baseUrl,Modal,fwaTabsetService,$stateParams,AuditDictServices){

		$scope.auditDictServices = AuditDictServices;
		AuditDictServices.initCodeListDatas();
		$scope.requestParam = {
            page:"1",
            pageSize:"20"
        };
        $scope.communityService = CommunityService;
        CommunityService.initCodeListDatas();
        $scope.UrlParams = $stateParams;
		$scope.CaseAuditProjectAddService = CaseAuditProjectAddService;
		
		
		

		$scope.selectedTab = $scope.tabs[0];
		$scope.currentTabIndex = 0;

        $scope.problemtab = [ {label:'事件处理',id:0,url:'views/hcpms/audit/caseAduitDispathDealProblem.html'},
            {label:'调查结果',id:1,url:'views/hcpms/audit/caseAduitProjectDetails.html'},
            {label:'稽核项目',id:2,url:'views/hcpms/audit/caseAuditPorject_view.html'},
            {label:'稽核结果',id:3,url:'views/hcpms/audit/caseAduitCaseAdd_view.html'}];

        $scope.selectedTable = $scope.problemtab[0];
        $scope.tabIndex = 0;
        $scope.tabClicks = function(tab) {
            $scope.selectedTabs = tab;
            $scope.tabIndex=tab.id;

            if($scope.tabIndex==0){
                initdealPorblemData();
            }
            if($scope.tabIndex == 1){
                initProblem();
            }
            if($scope.tabIndex==2){
                //选中tab抛出改变窗口事件
                setTimeout(function(){
                    $(window).trigger('resize');
                },0);
                auditProject();
            }
            if($scope.tabIndex==3){
                gettotalDeduction();
            }
        }
		
		//初始化请求参数
         $scope.caseCode="";
        var params = function (){
            var problemNo = "";
            var  caseCode="";
            if($stateParams.problemNo && !angular.isUndefined($stateParams.problemNo) ){
                problemNo = $stateParams.problemNo;
            }
            if($stateParams.caseCode && !angular.isUndefined($stateParams.caseCode) ){
                caseCode = $stateParams.caseCode;
            }
            var params = {
                caseCode:caseCode,
                problemNo:problemNo,
                page:$scope.requestParam.page,
                pageSize:$scope.requestParam.pageSize
            }

            return params;
        }

        /**
         * 初始化医疗机构数据
         */
        function initdealPorblemData(){
            var parameter=params();
            CaseAuditProjectAddService.loadDealProblemData(parameter).success(function(response){
                 $scope.treatmentOpinion = response.result.treatmentOpinion;
                 $scope.auditOpinion = response.result.auditOpinion;
            });
        }
        function  initProblem (){
            var parameter = params();
            CaseAuditProjectAddService.queryOpinionData(parameter).success(function(response){
                $scope.treatmentOpinions = response.result.treatmentOpinion;
                $scope.auditOpinions = response.result.auditOpinion;
                $scope.audit = response.result.audit;
            });
        }
        $scope.columns = [
            {label:'项目名称',map:'projectName',width:'20%'},
            {label:'结算方式',map:'treatTypeName',width:'20%'},
            {label:'不合理费用',map:'deductionAmmountStr',width:'20%'},
            {label:'备注',map:'remark',width:'40%'}
                 ];
        /**
         * 稽核项目
         */
        $scope.tableData=[];
        function auditProject()
        {
           $scope.ammountCounts();
        }
         function initPorject()
         {
             var parameter=params();
             CaseAuditProjectAddService.queryAuditProject(parameter).success(function(response)
             {
                 $scope.tableData=response.result.auditProjectList;
             });
         }
        $scope.param={};
        $scope.initCaseDetail={};
        function initAudtiProject()
        {
            $scope.param.caseCode = $stateParams.caseCode;
            CaseAuditProjectAddService.getMeldicalInfo($scope.param).success(function(data){
                if (data.state == '0') {
                    if(data.result){
                        $scope.initCaseDetail = data.result;
                        $scope.auditFile=data.result;
                    }
                }
            });
        }
        /**
         * 获取不合理费用
         */
        $scope.caseObj={};
        var caseObj={};
        $scope.caseDetail={};
        function gettotalDeduction()
        {
            auditProject();
        }
          $scope.medical={};
          $scope.medicalCount="";
        /**
         * 初始化医疗机构数据和医护人员信息和参保人信息
         */
        $scope.medicalCode='';
        function initMedicalData(){
            var parameter={
            		problemNo:$stateParams.caseCode
            };
            CaseCommonService.loadMedicalInfoList(parameter).success(function(response){
                $scope.medicalData2=response.medicalBean.medicalList;
                if($scope.medicalData2.length>0)
                {
                    if($scope.medicalData2[0].medicalCode)
                    {
                        $scope.medicalCode=$scope.medicalData2[0].medicalCode;
                    }
                }
                $scope.staffData2=response.staffBean.staffList;
                $scope.insuranceData2=response.insuranceBean.insuranceList;
                CaseCommonService.initStaffAndInsuranceTempList($scope);
                //更新当前页面数据
                WarningScreenService.findPointCutTempScose(
                    WarningAddService.warningMarks,$stateParams.caseCode,'02',
                    $scope.medicalData2[0],$scope.staffData2,$scope.insuranceData2);
            });
        }

        /**
         * 初始化事件数据对象
         */
        $scope.initProblemData= function(){
            var parameter=params();
            var parameters={businessId:$stateParams.caseCode,
                moduleType:'jhModule',
                childModuleType:'audit',
                businessType:'11'};
            CaseCommonService.loadCaseData(parameter).success(function(response){
                $scope.caseObj = response.result.case1;
                $scope.ammountCount=$scope.caseObj.totalDeductionStr;
                $scope.caseDetail =  $scope.caseObj;
                $scope.caseDetail.opinion=$scope.caseDetail.pinions;
                if($scope.caseDetail.opinionDesc)
                {
                    $scope.caseDetail.originalOpinionDesc=$scope.caseDetail.opinionDesc;
                };

                CaseAuditDispathReviewDetailResultService.loadStorageData(parameters).success(function(response)
                {
                    if(response.result)
                    {
                        $scope.caseDetail.auditDate=response.result.auditDate;
                        $scope.caseDetail.periodBeginDates=response.result.periodBeginDates;
                        $scope.caseDetail.periodEndDates=response.result.periodEndDates;
                        $scope.caseDetail.auditSummary=response.result.auditSummary;
                        $scope.caseDetail.opinionDesc=response.result.opinionDesc;
                        $scope.ammountCount=response.result.totalDeductionStr;
                        if(response.result.notificationDTO)
                        {
                            $scope.auditFile=response.result.notificationDTO;
                            $scope.initCaseDetail=response.result.notificationDTO;
                        }
                        if(response.result.projectList)
                        {
                            $scope.tableData=response.result.projectList;
                        }
                    }
                    if(!$scope.initCaseDetail.sealDate)
                    {
                        CommunityService.initDate("yyyy-MM-dd").success(function(res) {
                            $scope.initCaseDetail.sealDate = res.formatDate;
                        });
                    }
                });
            });
        }



		//隐藏扣分以及删除按钮
		$scope.mouseoutShow = function(data){
			data.show = false;
		}
		
        //显示扣分以及删除按钮
		$scope.mouseoverShow = function(data){
			data.show = true;
		}
        /**
         * 返回
         */
        $scope.goBack = function () {
		   	WarningAddService.warningMarks = WarningAddService.warningMarkTemps;//初始化扣分参数

            if($stateParams.urlFlag){
                var urlFlag =  $stateParams.urlFlag;
                fwaTabsetService.closeTab('caseAudit','workingArea.transactorle',{urlFlag:urlFlag});
            }else
            {
                $state.go("caseAudit.caseAuditList");
            }
        };
        
        /**
         * 点击医疗机构量事件
         * 
         */
        $scope.$on('fwaInvolve.medicalCountClick',function(){
     	   CaseCommonService.viewMedicalDetail($scope);
        });

        /**
         * 点击医务人员总数量事件
         */
        $scope.$on('fwaInvolve.staffCountClick',function(){
        	CaseCommonService.viewStaffList($scope);
        });
        
        /**
         * 点击参保人总数量事件
         */
        $scope.$on('fwaInvolve.insuranceCountClick',function(){
        	CaseCommonService.viewInsurList($scope);
        });

        /**
         * 保存函数
         */
        $scope.loading = false;
        $scope.auditFile=null;
        $scope.submitForOpinion=function(flag)
        {
             //判断是否录入稽核告知函
            if(check())
            {
                $scope.loading = true;
                $scope.caseDetail.caseCode=$scope.UrlParams.caseCode;
                $scope.caseDetail.totalDeduction=$scope.ammountCount;
                $scope.caseDetail.tempFlag=flag;
                $scope.caseDetail.projectList=$scope.tableData;//稽核项目
                $scope.caseDetail.notificationDTO=$scope.auditFile;//稽核告知函
                $scope.caseDetail.tempState=1;//暂存标识：1，暂存；0，保存，2，退回岗位不同时
                $scope.caseDetail.warnMarkTempDetails=WarningAddService.warningMarks;
                $scope.caseDetail.opinion='0'; //默认异常
                var parameter=$scope.caseDetail;
                CaseAuditProjectAddService.addcaseInfo(parameter).success(function(data){
                    if(data.state=='true')
                    {
                        if(flag=='0')
                        {
                            $scope.goBack();
                        }
                        Modal.alert(data.msg);
                        WarningAddService.warningMarks = [];
                        
                        //更新当前页面数据
                        WarningScreenService.findPointCutTempScose(
                            WarningAddService.warningMarks,$stateParams.caseCode,'02',
                            $scope.medicalData2[0],$scope.staffData2,$scope.insuranceData2);
                        
                    }else
                    {
                        Modal.alert(data.msg);
                    }
                    $scope.loading = false;
                });
            }
            if(flag=='0')
            {
                $scope.saveReallyStaffAndInsuarnceInfo();
            }else
            {
                $scope.saveStaffAndInsuarnceInfo();
            }
        }

        /**
         * 调新增医务人员的回调函数
         *  parameter={
            * taskCode:'',
            * taskType:'',1事件,2案件
            * targetType:'',对象类型(1-医疗机构2-医生3-参保人)
            * targetCode:''
            * }
         */
        $scope.callStaffFun=function(array){
        	 CaseCommonService.addTempStaffList(array,$scope);
        }

        /**
         * 调新增参保人员的回调函数
         */
        $scope.callInsuranceFun=function(array){
        	 CaseCommonService.addTempInsuranceListInfo(array,$scope);
        }


        /**
         * 医务人员删除
         */
        $scope.$on('fwaInvolve.staffDel',function(e,data){
            Modal.confirm('确认删除医务人员'+data.name+'吗？',function(){
                WarningScreenService.deleteMark(WarningAddService.warningMarks,2,data);//mark:1.机构，2.医务人员，3.参保人
                CaseCommonService.deleteTempStaffList(data,$scope);
            });


        });

        /**
         * 参保人员删除
         */
        $scope.$on('fwaInvolve.insuranceDel',function(e,data){
     	   
     	   Modal.confirm('确认删除参保人员'+data.name+'吗？',function(){
 				WarningScreenService.deleteMark(WarningAddService.warningMarks,3,data);//mark:1.机构，2.医务人员，3.参保人
 				 CaseCommonService.deleteTempInsuranceInfoList(data,$scope);
 			});
     	   
          });
        /**
         * 新增医护人员事件
         */
        $scope.$on('fwaInvolve.staffAdd',function(){
            CaseCommonService.addStaffFun($scope);

        });
        /**
         * 新增参保人员事件
         */
        $scope.$on('fwaInvolve.insuranceAdd',function(){
            CaseCommonService.addInsuranceFun($scope);

        });

        /**
         * 医疗机构扣分事件
         */
        $scope.$on('fwaInvolve.medicalDeduction',function(e,v){
            $scope.marking (1,v, v.medicalCode, v.orgType);
        });
        /**
         * 医务人员扣分事件
         */
        $scope.$on('fwaInvolve.staffDeduction',function(e,v){
            $scope.marking(2,v,$scope.medicalCode,'');
        });
        //扣分 mark：1.机构扣分，2.医务人员扣分，3参保人员扣分,data:数据集合
        $scope.marking = function(mark,data,medicalCode,orgType){
            var medicalCodeTemp=null;
            if(medicalCode&&!angular.isUndefined(medicalCode)){
                medicalCodeTemp = medicalCode;
            }
            if(mark != 1 && medicalCodeTemp == null){
                Modal.alert("请先增加医疗机构信息！");
                return null;
            }else{
                medicalCode = medicalCodeTemp;
            }
            markData(mark,data,medicalCode,orgType);//扣分数据参数加载
            var modalInstance = $modal.open({
                templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningDeductionDialog_view.html',
                backdrop:'static',
                size:'sm',
                scope: $scope,
                //					  scope:scope,
                controller: 'WarningDeductionDialogCtrl'
            });
            //接收返回数据
            modalInstance.result.then(function(item) {
                if (!WarningAddService.warningMarks) {
                    WarningAddService.warningMarks = [];
                }
                WarningAddService.warningMarks = item;
                //更新当前页面数据
     		   	WarningScreenService.findPointCutTempScose(
     		   		item,$stateParams.caseCode,'02',
     		   	$scope.medicalData2[0],$scope.staffData2,$scope.insuranceData2);
                
            });
        }
        //扣分数据参数加载
        var markData = function(mark,data,medicalCode,orgType){
            WarningAddService.mark = mark;
            WarningAddService.warningMarkData = {
                orgType:orgType,//0.机构，1.药店
                medicalCode:medicalCode,//medicalCode:所属机构编号
                code:data.selfCode,//code:编号
                name:data.name,//name:名称
                caseType:'02',//案件类型caseType：01.预警,02.稽核
                caseNo: $stateParams.caseCode,//事件编号
                happenDate: $scope.caseObj.auditDate,//稽核时间
                punishDateStart: $scope.caseObj.periodBeginDates,// 稽核开始日期
                punishDateEnd: $scope.caseObj.periodEndDates,// 稽核结束日期
                warningMarks:WarningAddService.warningMarks
            };
        }

        function check()
        {
        	var dateReg =/^\d{4}-\d{2}-\d{2}$/; 
            //判断稽核告知函是否录入
            if(!$scope.auditFile.auditDate || !$scope.auditFile.periodBeginDates ||  !$scope.auditFile.periodEndDates ||
                !$scope.auditFile.auditSummary || !$scope.auditFile.opinionDesc)
            {
                Modal.alert('请先录入完整的稽核告知函！');
                return false;
            }
            if(!dateReg.test($scope.caseDetail.auditDate))
            {
                Modal.alert('稽核日期为必填项,并且必须输入正确的日期格式(yyyy-MM-dd)！');
                return false;
            } else if(!dateReg.test($scope.caseDetail.periodBeginDates) || !dateReg.test($scope.caseDetail.periodEndDates))
            {
                Modal.alert(' 稽核时段为必填项,并且必须输入正确的日期格式(yyyy-MM-dd)！');
                return false;
            }else if(!$scope.caseDetail.auditSummary)
            {
                Modal.alert(' 稽核摘要为必填项！');
                return false;
            }
            else if(!$scope.caseDetail.opinionDesc)
            {
                Modal.alert('处理意见为必填项！');
                return false;
            }
            return true;
        }

        /**
         * 医疗机构扣分
         */
        $scope.pointsMedical=function(id)
        {
            var problemNo=$scope.UrlParams.caseCode;
            fwaTabsetService.selectTab('pointsMedical',{id:id,problemNo:problemNo},false);
        }

        /**
         * 根据案件编号获取稽核项目不合理费用总额
         */
        $scope.ammountCount = "0.00";
        //计算合计金额
         $scope.ammountCounts=function() {
            var countNum = 0;
            angular.forEach($scope.tableData,function(data,index){
                countNum = countNum + parseFloat(data.deductionAmmount) * 100;
            });
            $scope.ammountCount = (countNum/100).toFixed(2);
        }
        /**
         * 查看案件来源
         */
            //弹窗
        $scope.$on('fwaAuditLeft.showModal',function(){
            $scope.caseObj=$scope.caseDetail;
            CaseCommonService.showCaseFromSourceDialog($scope);
        });
        /**
         * 新增稽核项目
         */
            //弹窗
        $scope.addAuditProject = function(){
            $modal.open({
                templateUrl:'auditProjectAdd_view.html',
                backdrop:'static',
                size:'sm',
                controller: function($scope, $modalInstance,Modal,CommunityService,$stateParams){
                    $scope.communityService = CommunityService;
                    CommunityService.initCodeListDatas();
                    var visitTypeDatas = CommunityService.visitTypeDatas;
                    var auditFeeTypeDatas=CommunityService.auditFeeTypeDatas;
                    $scope.auditProject = {};

                    //关闭弹窗
                    $scope.onOk = function() {
                        $modalInstance.dismiss();
                    }
                    

                    //确定事件
                    $scope.confirm = function() {
                        if(!$scope.auditProject.treatType){
                            Modal.alert("就诊类型为必填项！");
                            return false;
                        }
                        if(!$scope.auditProject.deductionAmmount){
                            Modal.alert("不合理费用为必填项");
                            return false;
                        } else {
                        	var _money =$scope.auditProject.deductionAmmount;
                        	if(isNaN(_money)){
                        		Modal.alert('输入金额数值不正确,请输入有效数值！');
                        		return false;
                        	}else{
                        		var str = parseFloat(_money)+"";
                        		var la = str.split(".");
                        		if(la.length==1){
                        			str+=".00";
                        		}
                        		var _num = parseFloat(str).toFixed(2);
                        		if(_num <=0 ){
                        			Modal.alert('输入金额数值不正确,请输入有效数值！');
                            		return false;
                        		}else if(_num>99999999.99){
                                    Modal.alert('输入金额数值超出范围！');
                                    return false;
                                }
                        		$scope.auditProject.deductionAmmount = _num;
                        		$scope.auditProject.deductionAmmountStr = _num;
                        	}
                        }
                        if(!$scope.auditProject.invoiceType){
                            Modal.alert("项目名称为必填项！");
                            return false;
                        }
                        angular.forEach(visitTypeDatas,function(totalCheck,i){
                           if($scope.auditProject.treatType==totalCheck.code)
                           {
                               $scope.auditProject.treatTypeName=totalCheck.name;
                               $scope.auditProject.treatType=totalCheck.code
                           }
                        });
                        angular.forEach(auditFeeTypeDatas,function(totalCheck,i){
                            if($scope.auditProject.invoiceType==totalCheck.code)
                            {
                                $scope.auditProject.projectName=totalCheck.name;
                                $scope.auditProject.invoiceType=totalCheck.code;
                            }
                        });
                        $scope.auditProject.caseCode= $stateParams.caseCode;
                        $modalInstance.close($scope.auditProject);
                    }
                }
            }).result.then(function(item) {
                    if (item) {
                        $scope.tableData.push(item);
                        $scope.tabClicks($scope.problemtab[2]);
                    }
                });
        }
        /**
         * 新增稽核告知函
         */
            //弹窗
        $scope.auditNotification = function(){
            var auditSummary = $scope.caseDetail.auditSummary;
            var opinionDesc = $scope.caseDetail.opinionDesc;
            var auditDate= $scope.caseDetail.auditDate;
            var periodBeginDates= $scope.caseDetail.periodBeginDates;
            var periodEndDates= $scope.caseDetail.periodEndDates;
            var scope = $scope.$new();
            $modal.open({
                templateUrl:baseUrl+'views/hcpms/audit/auditNotificationAdd_view.html',
                backdrop:'static',
                size:'sm',
                scope:scope,
                controller: function($scope, $modalInstance,Modal,CommunityService,$stateParams){
                    $scope.caseDetail={};
                    $scope.caseDetail.caseCode = $stateParams.caseCode;
                    if ($scope.initCaseDetail) {
                            $scope.caseDetail = $scope.initCaseDetail;
                            $scope.caseDetail.auditSummary = auditSummary;
                            $scope.caseDetail.opinionDesc = opinionDesc;
                            $scope.caseDetail.auditDate = auditDate;
                            $scope.caseDetail.periodBeginDates = periodBeginDates;
                            $scope.caseDetail.periodEndDates = periodEndDates;
                        }
                    //确定事件
                    $scope.confirm = function() {
                    	var dateReg =/^\d{4}-\d{2}-\d{2}$/; 
                        if(!dateReg.test($scope.caseDetail.auditDate))
                        {
                            Modal.alert('案发日期为必填项,并且必须输入正确的日期格式(yyyy-MM-dd)！');
                            return false;
                        }
                        if(!dateReg.test($scope.caseDetail.periodBeginDates) || !dateReg.test($scope.caseDetail.periodEndDates))
                        {
                            Modal.alert(' 稽核时段为必填项,并且必须输入正确的日期格式(yyyy-MM-dd)！');
                            return false;
                        }
                        if(!$scope.caseDetail.auditSummary)
                        {
                            Modal.alert(' 稽核摘要为必填项！');
                            return false;
                        }
                        if(!$scope.caseDetail.opinionDesc)
                        {
                            Modal.alert('处理意见为必填项！');
                            return false;
                        }
                       $modalInstance.close($scope.caseDetail);

                    }
                    //关闭弹窗
                    $scope.onOk = function() {
                        $modalInstance.dismiss();
                    }
                }
            }).result.then(function(item) {
                    $scope.auditFile=item;
                    $scope.caseDetail.auditSummary = item.auditSummary;
                    $scope.caseDetail.opinionDesc = item.opinionDesc;
                    $scope.caseDetail.auditDate = item.auditDate;
                    $scope.caseDetail.periodBeginDates = item.periodBeginDates;
                    $scope.caseDetail.periodEndDates = item.periodEndDates;
            });
        }
        var checkRows = [];
        function findCheck(d) {
            for(var i=0;i< checkRows .length;i++) {
                var checkedData =  checkRows [i];
                if(checkedData.itemId == d.itemId) {
                    return i;
                }
            }
            return -1;
        }

        $scope.$on('fwatable.checked', function(e,d){
            if(findCheck(d) == -1) {
                checkRows .push(d);
            }
        });

        $scope.$on('fwatable.unchecked', function(e,d){
            var index = findCheck(d);
            if(index != -1) {
                checkRows.splice(index,1);
            }
        });
        /**
         * 稽核项目--删除
         * @param params
         */
        $scope.deleteAuditProject = function(){
            var projectList=[];
            if (checkRows.length == 0) {
                Modal.alert("请勾选删除项！");
                return;
            }else
            {
                angular.forEach($scope.tableData,function(totalCheck,i){
                    if(!totalCheck.checked)
                    {
                        projectList.push(totalCheck);
                    }
                });
                Modal.confirm('确认删除吗？',function(){
                    $scope.tableData=projectList;
                    $scope.tabClicks($scope.problemtab[2]);
                });
            }
        };
        initMedicalData();
        initPorject();
        initAudtiProject();//初始化稽核告知函
        $scope.initProblemData();
        $scope.ammountCounts();
        $scope.tabClicks($scope.problemtab[3]);
        
        
        /**
         * 对医务人员和参保人员的暂存信息保存
         */
        $scope.saveStaffAndInsuarnceInfo=function(){
            $scope.saveType="temp";
            saveStaffListInfo();
            saveInsuranceInfo();
        }


        /**
         * 对医务人员和参保人员的真实数据信息保存
         */
        $scope.saveReallyStaffAndInsuarnceInfo=function(){
            $scope.saveType="save";
            saveStaffListInfo();
            saveInsuranceInfo();
        }

 	   /**
 	    * 暂存的时候对医务人员进行的保存
 	    */
        function saveStaffListInfo(){
 	   CaseCommonService.saveTempStaffListInfo($scope,'2','2',$stateParams.caseCode);
 	   
        }
        
        /**
 	    * 暂存的时候对参保人员进行的保存
 	    */
        function saveInsuranceInfo(){
     	   CaseCommonService.saveTempInsuranceListInfo($scope,'2','3',$stateParams.caseCode);
        }
      
 	       
        
   }]);
})();
